package aishua.com.mytestapplist.mimaxiang;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Vibrator;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;

import aishua.com.mytestapplist.MyApplication;


public class DragGridView extends GridView {
    private final int PRESS_TIME = 800;

    private int mDownX;
    private int mDownY;

    private int mMoveX;
    private int mMoveY;

    private int mOffset2Top;

    private int mOffset2Left;
    private int mPointToItemTop;
    private int mPointToItemLeft;
    private int mStatusHeight;
    private boolean isDraging;
    private Bitmap mBitmap;
    private int mTouchPostiion;
    private View mTouchItemView;
    private Vibrator mVibrator;
    private ImageView mDragImageView;
    private WindowManager mWindowManager;
    private WindowManager.LayoutParams mWindowLayoutParams;
    private OnChanageListener onChanageListener;

    private Handler mHandler = new Handler();

    private int mDownScrollBorder;
    private int mUpScrollBorder;
    private static final int speed = 20;

    public DragGridView(Context context) {

        this(context, null);
    }

    public DragGridView(Context context, AttributeSet attrs) {

        this(context, attrs, 0);
    }

    public DragGridView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mStatusHeight = getStatusHeight(context);
        mVibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
        mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:

                mHandler.postDelayed(mLongClickRunnable, PRESS_TIME);
                mDownX = (int) ev.getX();
                mDownY = (int) ev.getY();

                mTouchPostiion = pointToPosition(mDownX, mDownY);
                if (mTouchPostiion == AdapterView.INVALID_POSITION) {
                    return super.dispatchTouchEvent(ev);
                }

                mTouchItemView = getChildAt(mTouchPostiion - getFirstVisiblePosition());

                mPointToItemTop = mDownY - mTouchItemView.getTop();
                mPointToItemLeft = mDownX - mTouchItemView.getLeft();
                mOffset2Top = (int) (ev.getRawY() - mDownY);
                mOffset2Left = (int) (ev.getRawX() - mDownX);

                mDownScrollBorder = getHeight() / 4;
                mUpScrollBorder = getHeight() * 3 / 4;

                mTouchItemView.setDrawingCacheEnabled(true);
                mBitmap = Bitmap.createBitmap(mTouchItemView.getDrawingCache());
                mTouchItemView.destroyDrawingCache();
                break;
            case MotionEvent.ACTION_MOVE:
                int moveX = (int) ev.getX();
                int moveY = (int) ev.getY();

                if (ev.getY() > getHeight() || ev.getY() < 0) {
                    onStopDrag();
                }

                if (!isTouchInItem(mTouchItemView, moveX, moveY)) {
                    mHandler.removeCallbacks(mLongClickRunnable);
                    mHandler.removeCallbacks(mScrollRunnable);
                }
                break;
            case MotionEvent.ACTION_UP:
                mHandler.removeCallbacks(mLongClickRunnable);
                break;
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        if (isDraging && mDragImageView != null) {
            switch (ev.getAction()) {
                case MotionEvent.ACTION_MOVE:
                    mMoveX = (int) ev.getX();
                    mMoveY = (int) ev.getY();

                    onDragItem(mMoveX, mMoveY);
                    break;
                case MotionEvent.ACTION_UP:
                    onStopDrag();
                    break;
            }
            return true;
        }
        return super.onTouchEvent(ev);
    }

    private Runnable mLongClickRunnable = new Runnable() {
        @Override
        public void run() {
            MyApplication.isDraw = true;
            isDraging = true;
            mVibrator.vibrate(50);
            mTouchItemView.setVisibility(View.INVISIBLE);
            createDragView(mBitmap, mDownX, mDownY);
        }
    };

    private void createDragView(Bitmap bitmap, int downX, int downY) {
        mWindowLayoutParams = new WindowManager.LayoutParams();
//        mWindowLayoutParams.format = PixelFormat.TRANSLUCENT;
        mWindowLayoutParams.gravity = Gravity.TOP | Gravity.LEFT;
        mWindowLayoutParams.x = downX - mPointToItemTop + mOffset2Left;
        mWindowLayoutParams.y = downY - mPointToItemTop + mOffset2Top - mStatusHeight;
        mWindowLayoutParams.alpha = 0.6f;
        mWindowLayoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
        mWindowLayoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        mWindowLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
        mDragImageView = new ImageView(getContext());
        mDragImageView.setImageBitmap(bitmap);
        mWindowManager.addView(mDragImageView, mWindowLayoutParams);
    }

    private void removeDragView() {
        if (mDragImageView != null) {
            mWindowManager.removeView(mDragImageView);
            mDragImageView = null;
        }
    }

    private boolean isTouchInItem(View dragView, int x, int y) throws NullPointerException {
        if (dragView == null) {
            return false;
        }
        int leftOffset = dragView.getLeft();
        int topOffset = dragView.getTop();
        if (x < leftOffset || x > leftOffset + dragView.getWidth()) {
            return false;
        }
        if (y < topOffset || y > topOffset + dragView.getHeight()) {
            return false;
        }
        return true;
    }

    private void onDragItem(int moveX, int moveY) {
        mWindowLayoutParams.x = moveX - mPointToItemLeft + mOffset2Left;
        mWindowLayoutParams.y = moveY - mPointToItemTop + mOffset2Top - mStatusHeight;
        mWindowManager.updateViewLayout(mDragImageView, mWindowLayoutParams);

        onSwapItem(moveX, moveY);

        mHandler.post(mScrollRunnable);
    }

    private void onSwapItem(int moveX, int moveY) {
        int tempPosition = pointToPosition(moveX, moveY);

        if (tempPosition != mTouchPostiion && tempPosition != AdapterView.INVALID_POSITION) {
            getChildAt(tempPosition - getFirstVisiblePosition()).setVisibility(View.INVISIBLE);
            getChildAt(mTouchPostiion - getFirstVisiblePosition()).setVisibility(View.VISIBLE);
            if (onChanageListener != null) {
                onChanageListener.onChange(mTouchPostiion, tempPosition);
            }
            mTouchPostiion = tempPosition;
        }
    }

    private void onStopDrag() {
        MyApplication.isDraw = false;
        isDraging = false;
        View view = getChildAt(mTouchPostiion - getFirstVisiblePosition());
        if (view != null) {
            view.setVisibility(View.VISIBLE);
        }
        removeDragView();
    }

    public void setOnChangeListener(OnChanageListener onChanageListener) {
        this.onChanageListener = onChanageListener;
    }

    private Runnable mScrollRunnable = new Runnable() {
        @Override
        public void run() {
            int scrollY;
            if (mMoveY > mUpScrollBorder) {
                scrollY = speed;
                mHandler.postDelayed(mScrollRunnable, 25);
            } else if (mMoveY < mDownScrollBorder) {
                scrollY = -speed;
                mHandler.postDelayed(mScrollRunnable, 25);
            } else {
                scrollY = 0;
                mHandler.removeCallbacks(mScrollRunnable);
            }

            smoothScrollBy(scrollY, 10);
        }
    };

    private int getStatusHeight(Context context) {
        int statusHeight = 0;
        Rect localRect = new Rect();
        ((Activity) context).getWindow().getDecorView().getWindowVisibleDisplayFrame(localRect);
        statusHeight = localRect.top;
        if (0 == statusHeight) {
            Class<?> localClass;
            try {
                localClass = Class.forName("com.android.internal.R$dimen");
                Object localObject = localClass.newInstance();
                int i5 = Integer.parseInt(localClass.getField("status_bar_height").get(localObject).toString());
                statusHeight = context.getResources().getDimensionPixelSize(i5);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return statusHeight;
    }

    public interface OnChanageListener {
        void onChange(int from, int to);
    }
}